package org.stvd.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.support.UserDetail;
import org.stvd.common.security.support.UserSessionInfo;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 用户会话控制类
 * @author houzx
 */
@Api(tags = "系统会话接口类")
@Controller
@RequestMapping("/admin/session")
public class UserSessionController extends BaseController{
    
    @Autowired
    private SessionRegistry sessionRegistry ;
    
    private String tmpURL = "/admin/session/";
    
    /*
     * 获取登录用户的信息
     */
    public List<UserSessionInfo> loadSessionInfo(String userId){
        //获取用户对象
        List<Object> loginObjs = sessionRegistry.getAllPrincipals();
        List<UserSessionInfo> userdetailList = new ArrayList<UserSessionInfo>() ;
        for(Object obj : loginObjs){
            if(obj instanceof UserDetail){
                UserDetail userTemp =(UserDetail) obj;
                //根据用户对象获取用户的session对象
                List<SessionInformation> sessionInformationList = sessionRegistry.getAllSessions(userTemp, false);
                for(SessionInformation sessionObj : sessionInformationList){
                    UserSessionInfo myUserSessionInfo = 
                        new UserSessionInfo(sessionObj.getPrincipal(),sessionObj.getSessionId(),sessionObj.getLastRequest());
                    if(sessionObj.isExpired()){
                        myUserSessionInfo.expireNow();
                    }
                    if(!myUserSessionInfo.isExpired() && 
                        (userId.equals("") || myUserSessionInfo.getPrincipal().getUsername().equals(userId))){
                        userdetailList.add(myUserSessionInfo);
                    }
                }
            }
        }
        return userdetailList;
    }
    
    /**
     * session管理
     * @return
     */
    @ApiIgnore
    @RequestMapping(value="management")
    public String userSessionManage(){
        String userId = "" ;
        if(request.getParameter("userId") != null){
            userId = request.getParameter("userId").trim();
        }
        //查询结果和记录数
        List<UserSessionInfo> userdetailList = loadSessionInfo(userId);
        Integer recordCount = userdetailList.size();
        int start = (pageNo - 1) * pageSize;   
        if (start==recordCount && start>0) {
            pageNo = pageNo - 1;
            if (pageNo > 0) { 
                start = (pageNo - 1) * pageSize;
            } else {
                start = 0;
            }
        }
        if (start > recordCount) {
            pageNo = 1;
            start = 0;
        }
        int end = start + pageSize;
        if(end > recordCount){
            end = recordCount;
        }
        List<UserSessionInfo> userSessionList = userdetailList.subList(start, end);
        map.put("recordCount", recordCount) ;   
        map.put("pageNo", pageNo) ;   
        map.put("userSessionList", userSessionList);
        return tmpURL + "UserSessionManage.html";
    }
    
    /**
     * 强制退出
     * @param sessionid
     * @param request
     * @param model
     */
    @ApiOperation(value = "强制退出系统")
    @ApiImplicitParam(value = "会话ID", name="sessionId", required = true, paramType = "query")
    @Log(title = "强制退出系统", businessType = BusinessType.FORCE)
    @PostMapping(value = "logout")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> userLogout(HttpServletRequest request, HttpServletResponse response){
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            String sessionId = request.getParameter("sessionId");
            SessionInformation sessionInfo = sessionRegistry.getSessionInformation(sessionId);
            if(sessionInfo != null){
                sessionInfo.expireNow();
                //删除session对象
                //sessionRegistry.removeSessionInformation(sessionInfo.getSessionId());
            }
            //清除cookie
            Cookie[] cookies = request.getCookies();
            if(cookies!=null && cookies.length>0){
                for(Cookie cookie : cookies){
                    if("ticket".equals(cookie.getName())) {
                        cookie.setPath("/");
                    }
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie  
                    response.addCookie(cookie);  
                }
            }
            result.setMsg("删除成功");
        } catch (Exception e) {
            result.setError("删除失败,失败原因:"+e.getMessage());
        }
        return result;
    }
}
